<?php

namespace app\common\model;

use app\api\model\User as UserModel;
use app\api\model\user\CouponLog as CouponLogModel;
use app\common\exception\BaseException;
use think\Hook;

/**
 * 订单模型
 * Class Order
 * @package app\common\model
 */
class Order extends BaseModel
{
    protected $name = 'order';

    /**
     * 订单模型初始化
     */
    public static function init()
    {
        parent::init();
        // 监听订单处理事件
        $static = new static;
        Hook::listen('order', $static);
    }

    /**
     * 订单商品列表
     * @return \think\model\relation\HasMany
     */
    public function goods()
    {
        return $this->hasMany('OrderGoods');
    }

    /**
     * 关联订单收货地址表
     * @return \think\model\relation\HasOne
     */
    public function address()
    {
        return $this->hasOne('OrderAddress');
    }

    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('User');
    }

    /**
     * 关联物流公司表
     * @return \think\model\relation\BelongsTo
     */
    public function express()
    {
        return $this->belongsTo('Express');
    }

    /**
     * 改价金额（差价）
     * @param $value
     * @return array
     */
    public function getUpdatePriceAttr($value)
    {
        return [
            'symbol' => $value < 0 ? '-' : '+',
            'value' => sprintf('%.2f', abs($value))
        ];
    }

    /**
     * 付款状态
     * @param $value
     * @return array
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 发货状态
     * @param $value
     * @return array
     */
    public function getDeliveryStatusAttr($value)
    {
        $status = [10 => '待发货', 20 => '已发货'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 收货状态
     * @param $value
     * @return array
     */
    public function getReceiptStatusAttr($value)
    {
        $status = [10 => '待收货', 20 => '已收货'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 收货状态
     * @param $value
     * @return array
     */
    public function getOrderStatusAttr($value)
    {
        $status = [10 => '进行中', 20 => '已取消', 21 => '待取消', 30 => '已完成'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 生成订单号
     * @return string
     */
    protected function orderNo()
    {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * 订单详情
     * @param $where
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        is_array($where) ? $filter = $where : $filter['order_id'] = (int)$where;
        return self::get($filter, ['goods.image', 'address', 'express']);
    }

    /**
     * 订单详情用于task任务
     * @param $order_id
     * @return Order|null
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public static function getUserOrderDetailForTask($order_id)
    {
        if (!$order = self::get([
            'order_id' => $order_id,
            'order_status' => ['<>', 20]
        ], ['goods' => ['image', 'sku', 'goods'], 'address', 'express'])) {
            throw new BaseException(['msg' => '订单不存在']);
        }
        return $order;
    }


    /**
     * 确认收货增加用户积分和设置会员
     * @param $order_id
     * @return false
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public static function grantUserPoints($order_id)
    {
        $orderDetail = self::getUserOrderDetailForTask($order_id);
        $userModel = UserModel::detail($orderDetail['user_id']);
        //判断是否会员升级
        if ($orderDetail['goods'][0]['is_enable_grade'] == 1) {
            UserModel::setUserGrade($userModel, $orderDetail['goods'][0]['grade_id']);
        }
        //判断订单发送返现劵还是积分
        if ($orderDetail['coupon_id'] > 0 && $userModel) {
            //增加用户积分
            if ($orderDetail['coupon_id'] == 1) {
                $describe = "用户购买：{$orderDetail['goods'][0]['goods_name']}";
                $userModel->setIncPoints($orderDetail['goods'][0]['user_return_points'], $describe, $orderDetail['goods'][0]['goods_id'], 20, 20);
            }
            // 发送现金券
            if ($orderDetail['coupon_id'] == 2) {
                CouponLogModel::setIncCoupon($userModel['user_id'], $orderDetail['order_no'], $orderDetail['goods'][0]['user_return_coupon'], $orderDetail['goods'][0]['user_return_coupon_days']);
            }
        }
        //增加用户消费总金额
//        $userModel->setInc('money', $orderDetail['pay_price']);
        //增加订单数
        $userModel && $userModel->setInc('order_num', 1);
    }

}
